<template>
  <div>
<div v-show="DatilModel === 'list'">
<maintain pagetype="list" @goDatil="goDatil" ></maintain>
  </div>
<div v-show="DatilModel === 'datil'">
  <h3 style="color:#999999">{{groupName}}</h3>
<hr/>
                            <el-button type="primary" size="small" @click="backPage" plain=""><i class="el-icon-arrow-left"></i> 返回</el-button>

<el-button type="primary" size="small" @click="changeInput()" v-if="$store.getters.getRoleTpye === 'admin' ||handelUpdateRole(5)">新增属性</el-button>

 <el-table
    :data="datilTableData"
    style="width: 100%" >
    <el-table-column
      prop="date"
      label="字段名" sortable
   >
    <template scope="scope" >
                   <span>{{ scope.row.infoName}}</span>
                        </template>
    </el-table-column>

  <el-table-column
      prop="name"
      label="缩略图" width="120"
   >

 <template scope="scope">
    <span><img :src="scope.row.iconUrl" style="width:100px;height:100px;" alt=""></span>
                  
                        </template>
    </el-table-column>

    <el-table-column
      prop="name"
      label="内容" sortable
width="200"
      
   >
 <template scope="scope">
                    <span>{{ scope.row.content}}</span>
                      
                        </template>
    </el-table-column>

    <el-table-column
      prop="name"
      label="内容类型" sortable
   >
 <template scope="scope">
                    <span>{{ handleContentType(scope.row.contentType)}}</span>
                        </template>
    </el-table-column>
    <!-- <el-table-column
      prop="name"
      label="链接"
   >
 <template scope="scope">
      <span>{{ scope.row.contentUrl}}</span>
                        </template>
    </el-table-column> -->

       <el-table-column
      prop="date"
      label="显示状态" sortable
   >
    <template scope="scope">
                            <span>{{scope.row.showStatus ?'显示':'隐藏'}}</span>
                        </template>
    </el-table-column>


  <el-table-column label="操作" width="400">  

                        <template scope="scope" >
                          <el-button type="text"  size="mini" icon="el-icon-upload2" :disabled="scope.$index === 0"  @click="doMove(scope.$index,true)">上移</el-button>
                          <el-button type="text"  size="mini" icon="el-icon-download"  :disabled="scope.$index === datilTableData.length-1"  @click="doMove(scope.$index,false)">下移</el-button>
                          
                          
                                       <el-button :type="scope.row.showStatus ?'danger':''" size="mini" @click="eidtAttributeHidden(scope.row)">{{scope.row.showStatus ?'隐藏':'显示'}}</el-button>
                            <el-button type="primary" size="mini" @click="changeInput(scope.row)" v-if="$store.getters.getRoleTpye === 'admin' ||handelUpdateRole(6)">编辑</el-button>
                            <el-button type="danger" size="mini" @click="delAttribute(scope.row)" v-if="$store.getters.getRoleTpye === 'admin' ||handelUpdateRole(7)">删除</el-button>
                            
                        </template>
      
    </el-table-column>
  </el-table>





 <el-dialog :title="infoEditFormPageType === 'add' ?'新增维护信息':'修改维护信息'" :visible.sync="arrModel" style="padding:20px 100px" center top="10vh" :close-on-click-modal='false'>



        <section class="header-block">
            <div class="operation-container">
                        <el-form :model="infoEditForm" :rules="infoEditFormRules" ref="infoEditForm" label-width="7em">

                <el-row :gutter="24" class="row-container">
                    <el-col :span="15" :offset="5">
                            <el-form-item label="维护信息名称" prop="infoName1">
                <el-input v-model="infoEditForm.infoName" ></el-input>
                            </el-form-item>
                    </el-col>
                </el-row>



                  <el-row :gutter="24" class="row-container">
                    <el-col :span="15" :offset="5">
                            <el-form-item label="内容名称" prop="content1">
                <el-input v-model="infoEditForm.content" ></el-input>
                            </el-form-item>
                    </el-col>
                </el-row>




      <el-row :gutter="24" class="row-container">
                    <el-col :span="15" :offset="5">
                          <el-form-item label="内容链接类型" prop="contentType1">
        <el-select v-model="infoEditForm.contentType" placeholder="请选择内容类型"      >
      <el-option label="图片" value="IMAGE"></el-option>
      <!-- <el-option label="链接" value="URL"></el-option> -->
      <el-option label="文字" value="TEXT"></el-option>
    </el-select>
  </el-form-item>
                    </el-col>

                </el-row>
<div v-if="infoEditForm.contentType === 'IMAGE'">
   <el-form-item  v-loading="loadding">
    <el-upload :action="uploadModel.uploadUrl" list-type="picture-card"
                 :on-preview="uploadModel.onPreview" 
                :on-remove="uploadModel.onRemove" 
                :on-success="uploadModel.onUploadSuccess" 
                :file-list="uploadModel.fileList"
                :on-progress="uploadModel.progress"
                :on-error="uploadModel.error"
                :before-upload="uploadModel.onBefore">
                    <i class="el-icon-plus"></i>
                </el-upload>
  </el-form-item>
<div style="    color: #fa5555;    font-size: 12px;" v-if="uploadModel.fileList.length === 0">请上传一张以上的图片</div>
</div>
  
          <el-row :gutter="24" class="row-container" v-if="infoEditForm.contentType === 'URL'">
                    <el-col :span="15" :offset="5">
                            <el-form-item label="链接内容" prop="contentUrl">
                <el-input v-model="infoEditForm.contentUrl" ></el-input>
                            </el-form-item>
                    </el-col>
                </el-row>

<div style="text-align:center">
       <el-form-item>


              <el-button @click="arrModel=false">取消</el-button>
    <el-button type="primary" @click="submitEditForm('infoEditForm')" :disabled="loadding"  element-loading-background="rgba(0, 0, 0, 0.8)">保存</el-button>
  </el-form-item>
    </div>
                        </el-form>
            </div>
        </section>
           
        </el-dialog>

        
</div>


<div v-show="DatilModel === 'car'"  >


 <el-row :gutter="24" class="row-container">
                    <el-col :span="12" v-loading="modelTableLoading">
<div v-loading="modelSelectLoading" >

  
      
<div style="text-align:center;padding:20px 0">    <el-button  @click="screenInit">选择筛选条件</el-button>
</div>
     
   </div>






    </el-col>
           <el-col :span="12" >

              <h2 style="    color: #999999;">已关联的车型</h2>


 <el-table
    :data="carIdList" 
    style="width: 100%" height="720">

<!-- @expand-change="changeColumn" -->
        <!-- <el-table-column type="expand" >
      <template slot-scope="props">
                    
 <el-table
    :data="datilTableData"
    style="width: 100%">


                      {{props.$index}}
                               </template>
    </el-table-column> -->

    <el-table-column
      prop="date"
      label="品牌" sortable
   >
    <template scope="scope" >
                   <span>{{scope.row.carModel ?scope.row.carModel.brandName:''}}</span>
                        </template>
    </el-table-column>
    <el-table-column
      prop="date"
      label="车系" sortable
   >
    <template scope="scope" >
                   <span>{{scope.row.carModel ?scope.row.carModel.seriesName:''}}</span>
                        </template>
    </el-table-column>


  <el-table-column
      prop="date"
      label="车型" sortable
   >
    <template scope="scope" >
                   <span>{{ scope.row.carModel ?scope.row.carModel.modelName:''}}</span>
                        </template>
    </el-table-column>


  <el-table-column label="操作">

                        <template scope="scope">
            <el-button type="danger" size="mini" @click="onsubmit">取消</el-button>

                        </template>
      
    </el-table-column>
  </el-table>


    </el-col>
             
                </el-row>


<div style="    text-align: center;padding:20px 0">
   <el-button type="primary" size="small" @click="backPage">返回</el-button>
     <el-button type="primary" size="small" @click="saveSelectCar()" v-show="DatilModel === 'car'">保存选择</el-button>
</div>

</div>

  <el-dialog  :visible.sync="imageDialogModel.show" >
                        <img width="100%" :src="imageDialogModel.imageUrl" alt="">
                    </el-dialog>
                    

  </div>
</template>

<script>
import * as Api from "@/api/Api.js";
import * as RoundApi from "@/api/RoundApi.js";
import * as Config from "@/api/Config.js";
import axios from "axios";
import maintain from "@/components/maintain/MaintainComponent";

export default {
  data() {
    var infoName = (rule, value, callback) => {
      
      if ((this.infoEditForm.infoName || "") === "") {
        callback(new Error("请输入维护信息名称"));
      }
      callback();
    };
    var content = (rule, value, callback) => {
      if ((this.infoEditForm.content || "") === "") {
        callback(new Error("请输入内容名称"));
      }
      callback();
    };
    var contentType = (rule, value, callback) => {
      if ((this.infoEditForm.contentType || "") === "") {
        callback(new Error("请选择内容链接类型"));
      }
      callback();
    };
    var uploadUrl = (rule, value, callback) => {
      if (this.infoEditForm.contentType === "IMAGE") {
        if (!this.infoEditForm.uploadModel.fileList.length > 0) {
          callback(new Error("请上传一张以上图片"));
        }
      }

      callback();
    };
  
    var contentUrl = (rule, value, callback) => {
      if (this.infoEditForm.contentType === "URL") {
        if ((this.infoEditForm.contentUrl || "") === "") {
          callback(new Error("请输入链接内容"));
        }
      }
      callback();
    };

    return {
        imageDialogModel: {
        show: false,
        imageUrl: ""
      },
      uploadModel: {
        uploadUrl: "",
        fileList: [],
        onRemove: (file, fileList) => {
          if(this.loadding){
              this.$message("请等待上传成功再操作")
                            this.loadding = false
            return
          }
          this.uploadModel.fileList = fileList;
        },
      
        onBefore:()=>{
          if(this.loadding){
            return false
          }
        },
        onPreview: file => {
          this.imageDialogModel.imageUrl = file.url;
          this.imageDialogModel.show = true;
        },

        onUploadSuccess: (response, file, fileList) => {
          console.log("上传成功");
          let dt = {
            name: "1.png",
            url: response.data.filename
          };
          this.uploadModel.fileList.push(dt);
          this.loadding = false;
        },
        error: () => {
          this.loadding = false;
        },
        progress: () => {
          this.loadding = true;
        },
        doPreview: () => {}
      },
      loadding: false,
      datilTableData: [],
      // 列表

      infoEditFormPageType: "add",
      //属性表单
      infoEditForm: {
        groupId: "",
        infoName: "",
        content: "",
        contentType: "",
        contentUrl: "",
        iconUrl: ""
      },
      //通用对象
      DatilModel: "list",
      groupName: "",
      groupId: "",
      screenShow: false,
      list: [],
      keyIds: [],
      modelTableShow: false,
      modelTableLoading: false, //表刷新时loadding
      modelSelectLoading: false, //匹配车型时loadding
      isInitSelectnnnn: false, //是否需要初始化默认的车型
      modelData: [], //列表对象
      carIdList: [],
      changeCarId: "",
      infoId: "",
      initHaveCarList: [],
      arrModel: false, //属性 新增 修改的弹窗

      category: [], //拉列表的时候独立分类对象

      //列表
      editerData: {
        show: false,
        selectedModel: [],
        model: {},
        propertyKey: {
          keyId: "",
          keyName: "",
          propertyType: ""
        }
      },

      // 验证对象

      infoEditFormRules: {
        infoName1: [{ validator: infoName, trigger: "blur" }],
        content1: [{ validator: content, trigger: "blur" }],
        contentType1: [{ validator: contentType, trigger: "blur" }]
      }
    };
  },

  methods: {
    doMove(index, isUpStatus) {
      let model = {
        infoId1: this.datilTableData[index].infoId,
        infoId2: ""
      };
      if (isUpStatus) {
        model.infoId2 = this.datilTableData[index - 1].infoId;
      } else {
        model.infoId2 = this.datilTableData[index + 1].infoId;
      }


  RoundApi.attributeSort(this, model).then(res => {
                this.goDatil({
              groupId: this.groupId,
              groupName: this.groupName
            });
        });


    },
    handleContentType(row) {
      switch (row) {
        case "IMAGE":
          return "图片";
        case "TEXT":
          return "文本";
        case "URL":
          return "链接";
      }
    },
    //属性 修改  新增
    editInfoEditForm() {
      if (this.infoEditFormPageType === "edit") {
        // 进行类型判断
        if (this.infoEditForm.contentType == "IMAGE") {
          if (this.uploadModel.fileList.length === 0) {
            return;
          }

          let contentUrl = [];
          this.uploadModel.fileList.forEach((item, index) => {
            contentUrl.push(item.url);
          });
          if (contentUrl.length > 0) {
            this.infoEditForm.iconUrl = contentUrl[0];
          } else {
            this.infoEditForm.iconUrl = "";
          }
          this.infoEditForm.contentUrl = contentUrl.join(",");
        } else if (this.infoEditForm.contentType == "TEXT") {
          this.infoEditForm.contentUrl = "";
          this.infoEditForm.iconUrl = "";
        } else {
          this.infoEditForm.iconUrl = "";
        }

        RoundApi.editInfoEditForm(this, this.infoEditForm).then(res => {
          if (res.retCode) {
            console.log("修改自定义属性", res);
            this.goDatil({
              groupId: this.groupId,
              groupName: this.groupName
            });
          }
        });
      } else if (this.infoEditFormPageType === "add") {
        // 进行类型判断
        if (this.infoEditForm.contentType == "IMAGE") {
          let contentUrl = [];
          this.uploadModel.fileList.forEach((item, index) => {
            contentUrl.push(item.url);
          });
          if (contentUrl.length > 0) {
            this.infoEditForm.iconUrl = contentUrl[0];
          } else {
            this.infoEditForm.iconUrl = "";
          }
          this.infoEditForm.contentUrl = contentUrl.join(",");
        } else if (this.infoEditForm.contentType == "TEXT") {
          this.infoEditForm.contentUrl = "";
        }
        this.infoEditForm.groupId = this.groupId;
        this.infoEditForm.showStatus = true;
        RoundApi.addInfoEditForm(this, this.infoEditForm).then(res => {
          if (res.retCode) {
            console.log("新增自定义属性", res);

            this.goDatil({
              groupId: this.groupId,
              groupName: this.groupName
            });
          }
        });
      } else {
        console.log("错误，页面无类型");
        return;
      }
      this.arrModel = !this.arrModel;
    },
    //属性  打开弹窗
    changeInput(row) {
      this.loadding = false;
      this.uploadModel.fileList = [];

      this.infoEditForm = {
        groupId: "",
        infoName: "",
        content: "",
        contentType: "",
        contentUrl: "",
        iconUrl: ""
      };

      this.arrModel = !this.arrModel;
      if (row) {
        console.log(' row.contentUrl', row.contentUrl)
        let infoEditForm = {};
        Object.assign(infoEditForm, row);
        this.infoEditForm = infoEditForm;
        if(row.contentUrl!=''){
        let fileList = [];
        row.contentUrl.split(",").forEach((item, index) => {
          fileList.push({
            name: index + ".jpg",
            url: item
          });
        });
        this.uploadModel.fileList = fileList;
        }


        this.infoEditFormPageType = "edit";
      } else {
        this.infoEditFormPageType = "add";
      }
    },
    delAttribute(row) {
      console.log(row);

      this.$confirm("此操作将永久删除该维保信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          RoundApi.delAttribute(this, { infoId: row.infoId }).then(res => {
            console.log(res);
            if (res.retCode) {
              this.$message("删除维保信息成功");
              this.goDatil({
                groupId: this.groupId,
                groupName: this.groupName
              });
            } else {
              this.$alert("删除维保信息失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //匹配车型
    saveSelectCar() {
      let addSelectModel = [];
      let moveSelectModel = [];

      this.editerData.selectedModel.forEach((item, caridIndex) => {
        let keyModel = false;
        //选择的
        this.initHaveCarList.forEach((model, modelIndex) => {
          //已有的
          if (item.modelId === model.carId) keyModel = true;
        });
        if (!keyModel) {
          addSelectModel.push(item.modelId);
        }
      });

      this.initHaveCarList.forEach((item, caridIndex) => {
        let keyModel = false;
        //已有的
        this.editerData.selectedModel.forEach((model, modelIndex) => {
          //选择的
          if (item.carId === model.modelId) keyModel = true;
        });
        if (!keyModel) {
          moveSelectModel.push(item.id);
        }
      });

      if (addSelectModel.length > 0) {
        let modelAdd = {
          infoId: this.infoId, //属性ID
          linkType: "CAR",
          linkIds: addSelectModel.join(",") //车型ID字符串 逗号隔开
        };
        RoundApi.maintainLinkCar(this, modelAdd).then(res => {
          if (res.retCode) {
            console.log("匹配车型", res);

            if (moveSelectModel.length > 0) {
              let modelMove = {
                maintainLinkIds: moveSelectModel.join(",")
              };
              RoundApi.cancelMaintainLinkCar(this, modelMove).then(res => {
                if (res.retCode) {
                  console.log("取消匹配车型", res);
                  this.selectCar({ infoId: this.infoId });
                }
              });
            } else {
              this.selectCar({ infoId: this.infoId });
            }
          }
        });
      } else {
        if (moveSelectModel.length > 0) {
          let modelMove = {
            maintainLinkIds: moveSelectModel.join(",")
          };
          RoundApi.cancelMaintainLinkCar(this, modelMove).then(res => {
            if (res.retCode) {
              console.log("取消匹配车型", res);
              this.selectCar({ infoId: this.infoId });
            }
          });
        } else {
          this.selectCar({ infoId: this.infoId });
        }
      }

      // modelSelectLoading
      // 完成 返回
      // 保存时 有延迟 导致下次进来还是上次的结果

      // this.backPage();
    },

    setSelected: function(val) {
      console.log(val);
      this.editerData.selectedModel = val;
    },
    setKeyIds: function(val) {
      this.keyIds = val;
    },
    //设置已选的车型   存在列表渲染之前设置无效  需要和onsubmit 这个function分开
    initSelectnnnn() {
      console.log("设置");

      this.editerData.selectedModel = [];
      this.initHaveCarList = [];
      console.log(this.carIdList.length);
      console.log(this.modelData.modelList.length);

      this.carIdList.forEach((carid, caridIndex) => {
        this.modelData.modelList.forEach((model, modelIndex) => {
          if (carid.carId === model.modelId) {
            this.editerData.selectedModel.push(model); //需要被动态选择的对象
            this.initHaveCarList.push(carid); //不变的已绑定的对象
          }
        });
      });

      setTimeout(() => {
        this.editerData.selectedModel.forEach((model, caridIndex) => {
          this.$refs.multipleTable.toggleRowSelection(model);
        });
        this.modelTableLoading = false;
      }, 1000);
    },
    onsubmit: function() {
      var params = new URLSearchParams();
      for (var i = 0; i < this.keyIds.length; i++) {
        params.append("keyIds", this.keyIds[i].keyId);
      }
      for (var i = 0; i < this.list.length; i++) {
        if (this.list[i].text.trim() != "")
          params.append(this.list[i].keyId, this.list[i].text);
      }

      this.modelTableShow = true;

      this.modelTableLoading = true;

      this.isInitSelectnnnn = true;
      axios
        .post(Config.g_service_url + "/screen", params)
        .then(
          function(response) {
            console.log("筛选之后", response.data.data);
            this.modelData = response.data.data;

            this.selectCar({ infoId: this.infoId });
            // this.initSelectnnnn();
          }.bind(this)
        )
        .catch(function(error) {});

      this.screenShow = false;
    },

    //初始化筛选字段
    screenInit: function() {
      if (this.list.length > 0) {
        this.screenShow = !this.screenShow;
      } else {
        RoundApi.initFilterList().then(res => {
          if (res.retCode) {
            console.log("初始化", res);
            this.list = res.data;
            this.screenShow = !this.screenShow;
          }
        });
      }
    },
    // changeColumn(row, expandedRows) {
    //   console.log(row, expandedRows);

    //   RoundApi.getCarIdListBymaintainId({
    //     maintainInfoId: row.infoId
    //   }).then(res => {
    //     if (res.retCode) {

    //       console.log("查询与该属性关联的车型ID列表", res);
    //     }
    //   });
    // },

    selectCar(row) {
      this.$refs.multipleTable.clearSelection();
      console.log(row);
      this.infoId = row.infoId;
      RoundApi.getCarIdListBymaintainId(this, {
        maintainInfoId: row.infoId
      }).then(res => {
        if (res.retCode) {
          console.log("查询与该属性关联的车型ID列表", res);
          this.carIdList = res.data;
          if (this.isInitSelectnnnn) {
            this.modelTableLoading = true;
            this.initSelectnnnn();
          }
        }
      });
      this.DatilModel = "car";
    },

    backPage() {
      if (this.DatilModel === "datil") {
        this.DatilModel = "list";
      } else if (this.DatilModel === "car") {
        this.DatilModel = "datil";
        this.$refs.multipleTable.clearSelection();
      }
    },
    goDatil(row) {
      this.DatilModel = "datil";
      this.groupId = row.groupId;
      this.groupName = row.groupName;

      RoundApi.MaintainDatil(this, { groupId: this.groupId }).then(res => {
        if (res.retCode) {
          console.log("分组详情", res);
          this.datilTableData = res.data;
        }
      });
    },

    //属性表单验证
    submitEditForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(valid);
          this.editInfoEditForm();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 数组删除元素
    removeByValue(arr, val) {
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] == val) {
          arr.splice(i, 1);
          break;
        }
      }
    },
    //隐藏 显示
    eidtAttributeHidden(row) {
      let model = {};
      Object.assign(model, row);
      model.showStatus = !model.showStatus;

      RoundApi.editAttribute(this, model).then(res => {
        console.log(res);
        if (res.retCode) {
          this.$message("保存成功");
          this.goDatil({
            groupId: this.groupId,
            groupName: this.groupName
          });
        } else {
          this.$alert("修改失败");
        }
      });
    }
  },
  mounted() {
    this.uploadModel.uploadUrl = Config.g_upload_url;
  },
  components: {
    maintain
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.el-button {
  font-size: 14px;
}

#screen-main {
  width: 100%;
  height: 500px;
  border: 1px solid #d8dce5;
  text-align: center;
}

#limit-switch {
  font-size: 15px;
}
.el-form-item__error {
  width: 20em;
}
.el-switch {
  margin-left: 16px;
  margin-bottom: 4px;
}
</style>